import json

import pymysql
from django.shortcuts import render
from django.http import HttpResponse,HttpResponseRedirect
from django.contrib.auth.decorators import login_required
from django.contrib import auth
from django.contrib.auth import authenticate, login
from  apitest.models import Apitest,Apistep,Apis,Set

# Create your views here.
def login(request):
    if request.POST:
        username = password = ''
        username = request.POST.get('username')
        password = request.POST.get('password')
        user = auth.authenticate(username=username, password=password)
        if user is not None and user.is_active:
            auth.login(request, user)
            request.session['user'] = username
            response = HttpResponseRedirect('/home/')
            return response
        else:
            return render(request, 'login.html', {'error': 'username or password error'})
    return render(request, 'login.html')

def test(request):
    return HttpResponse('hello test')

def home(request):
    return render(request, "home.html")

def logout(request):
    auth.logout(request)
    return render(request, "login.html")

#产品管理
from product.models import Product

# Create your views here.
def product_manage(request):
    username = request.session.get('user', '')
    product_list = Product.objects.all()
    return render(request, 'product_manage.html', {"user": username, 'products': product_list})

#接口管理
@login_required
def apitest_manage(request):
    if request.method == 'GET':
        apitest_list = Apitest.objects.all()
        username = request.session.get('user', '')
        return render(request, 'apitest_manage.html', {'user': username,"apitests": apitest_list})
    elif request.method == 'POST':
        # 获取复选框的值,是一个选中的数组
        tags = request.POST.getlist('my_checkbox')
        # for tag in tags:
        return HttpResponse(tags)
    else:
        pass
#接口步骤管理
@login_required
def apistep_manage(request):
    username = request.session.get('user', '')
    apistep_list = Apistep.objects.all()
    return render(request, 'apistep_manage.html', {'user': username, 'apisteps':apistep_list})
#单接口管理
@login_required
def apis_manage(request):
    username = request.session.get('user', '')
    apis_list = Apis.objects.all()
    return render(request, 'apis_manage.html', {'user': username, 'apises':apis_list})
#接口测试报告
@login_required
def test_report(request):
    username = request.session.get('user', '')
    apis_list = Apistep.objects.all()
    apis_count = Apis.objects.all().count() #接口总数
    db = pymysql.connect(user='root', password='123456', db='baihuidb',host='localhost')
    cursor = db.cursor()
    sql1 = 'SELECT count(id) from apitest_apis where apistatus=1'
    sql_res1 = cursor.execute(sql1)
    apis_pass_count = [row[0] for row in cursor.fetchmany(sql_res1)][0]
    sql2 = 'SELECT count(id) from apitest_apis where apistatus=0'
    sql_res2 =cursor.execute(sql2)
    apis_fail_count = [row[0] for row in cursor.fetchmany(sql_res2)][0]
    db.close()
    return render(request,"report.html",{"user":username, "apises": apis_list,"apiscounts":apis_count, "apis_pass_counts":apis_pass_count,"apis_fail_counts":apis_fail_count})

#设置管理
def set_manage(request):
    username = request.session.get('user', '')
    set_list = Set.objects.all()
    return render(request, 'set_manage.html', {'user': username, 'sets':set_list})

#用户管理
from django.contrib.auth.models import User
def set_user(request):
    user_list = User.objects.all()
    username = request.session.get('user', '')
    return render(request, 'set_user.html', {"user": username, "users": user_list})

#左侧菜单
# @login_required
def left(request):
    return render(request,"left.html")
#场景接口搜索功能
@login_required
def apisearch(request):
    username = request.session.get('user', '')
    search_apitestname = request.GET.get('apitestname',"")
    apitest_list = Apitest.objects.filter(apitestname__icontains=search_apitestname)
    return render(request,'apitest_manage.html',{'user':username, 'apitests': apitest_list})
#apis单一接口搜索功能
@login_required
def apissearch(request):
    username = request.session.get('user', '')
    search_apiname = request.GET.get('apiname',"")
    apis_list = Apis.objects.filter(apiname__icontains=search_apiname)
    return render(request,'apis_manage.html',{'user':username, 'apiss': apis_list})
#运行接口测试
# def test_apis(request):
#     # 新增文章
#     if request.method == 'GET':
#         tags = TagModel.objects.all()
#         return render(request, 'books_add.html', {'tags': tags})
#     elif request.method == 'POST':
#         title = request.POST.get('title', None)
#         content = request.POST.get('content', None)
#         blogModel = BlogModel(title=title, content=content, author=AuthorModel.objects.get(id=1))
#         blogModel.save()
#         # 获取复选框的值,是一个选中的数组
#         tags = request.POST.getlist('tags')
#         # 循环遍历所有选中的复选框,利用多对多的关系追加到数据库
#         for tag in tags:
#             blogModel.tag.add(tag)
#
#         return HttpResponseRedirect('book_add')
#     else:
#         return HttpResponse(u'是不被处理的请求方式')

#单接口测试
from django.http import JsonResponse
@login_required
def api_single_test(request):
    username = request.session.get('user', '')
    search_apiname = request.GET.get('apiname', "")

    if request.method == 'POST':
        # 获取前端发送的 JSON 数据
        data = json.loads(request.body)
        print('前端传到后台的数据: ',data)
        # 从 JSON 数据中获取所需的字段
        id = data.get('id')
        sql = 'SELECT * FROM apitest_apis WHERE id=' + str(id)
        # sql = 'select * from baihuidb.apitest_apis where  id = "1" '
        print('sql=',sql)
        sql_res = conndb_and_exesql(sql)
        # for i in sql_res:
        #     print('result=', i )
        print('type=',type(sql_res))
        print('sql_res=', sql_res)
        # curr_id_data = Apis.objects.filter(id=id)
        # for i in curr_id_data:
        #     print('当前Id对应的数据：',i)
        # name = data.get('name')

        # 处理数据...

        # 构建结果
        result = '处理结果：{} '.format(sql_res)

        # 将结果包装为 JSON 格式返回给前端
        response_data = {
            'result': result
        }

        return JsonResponse(response_data)

    return JsonResponse({'error': 'Invalid request.'})

def conndb_and_exesql(sql):
    '''默认连接的数据库，执行sql并返回查询结果。只支持查询'''
    db = pymysql.connect(user='root', password='123456', db='baihuidb', host='localhost')
    cursor = db.cursor(pymysql.cursors.DictCursor)
    try:
        cursor.execute(sql)
        result = cursor.fetchall()
        return result
    except Exception as e:
        print(f"发生错误：{e}")
        db.rollback()
    finally:
        cursor.close()
        db.close()

if __name__ == '__main__':
    s = 'SELECT * FROM apitest_apis WHERE id=1'
    print(conndb_and_exesql(s))


